package com.sxz.sbs.module.sale;

import android.content.Intent;
import android.graphics.Color;
import android.support.annotation.IdRes;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.bigkoo.pickerview.OptionsPickerView;
import com.bigkoo.pickerview.TimePickerView;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.sxz.sbs.R;
import com.sxz.sbs.app.AppConstant;
import com.sxz.sbs.applibrary.banner.AutoSlipBanner;
import com.sxz.sbs.applibrary.banner.AutoSlippingViewPager;
import com.sxz.sbs.applibrary.component.ClearEditText;
import com.sxz.sbs.applibrary.dialog.input.ValueInputBoardDialog;
import com.sxz.sbs.applibrary.state.StateLayout;
import com.sxz.sbs.base.BaseActivity;
import com.sxz.sbs.data.DataServer;
import com.sxz.sbs.event.AlterStallDetailEvent;
import com.sxz.sbs.event.EditPhotoEvent;
import com.sxz.sbs.http.retrofit.HttpParamMap;
import com.sxz.sbs.module.sale.mode.StallDetailBean;
import com.sxz.sbs.module.sale.mode.StallTypeBean;
import com.sxz.sbs.module.sale.presenter.StallDetailPresenter;
import com.sxz.sbs.module.sale.view.StallDetailView;
import com.sxz.sbs.other.FileBean;
import com.sxz.sbs.widget.CommonTitle;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 车位详情
 */
public class StallDetailActivity extends BaseActivity<StallDetailPresenter> implements StallDetailView {

    @BindView(R.id.iv_stall_detail_upload)
    ImageView ivStallDetailUpload;
    @BindView(R.id.avp_stall_detail_banner)
    AutoSlippingViewPager avpStallDetailBanner;
    @BindView(R.id.cet_stall_detail_title)
    ClearEditText cetStallDetailTitle;
    @BindView(R.id.cet_stall_detail_house)
    TextView cetStallDetailHouse;
    @BindView(R.id.cet_stall_detail_address)
    TextView cetStallDetailAddress;
    @BindView(R.id.cet_stall_detail_number)
    ClearEditText cetStallDetailNumber;
    @BindView(R.id.cet_stall_detail_floor)
    ClearEditText cetStallDetailFloor;
    @BindView(R.id.tv_stall_detail_type)
    TextView tvStallDetailType;
    @BindView(R.id.tv_stall_detail_area)
    TextView tvStallDetailArea;
    @BindView(R.id.tv_stall_detail_year)
    TextView tvStallDetailYear;
    @BindView(R.id.tv_stall_detail_build)
    TextView tvStallDetailBuild;
    @BindView(R.id.tv_stall_detail_object)
    TextView tvStallDetailObject;
    @BindView(R.id.rg_stall_detail)
    RadioGroup radioGroup;
    @BindView(R.id.radio_have)
    RadioButton rbHave;
    @BindView(R.id.radio_no)
    RadioButton rbNo;
    @BindView(R.id.cet_stall_detail_advantage)
    ClearEditText cetStallDetailAdvantage;
    @BindView(R.id.cet_stall_detail_min_price)
    TextView minPrice;
    @BindView(R.id.cet_stall_detail_max_price)
    TextView maxPrice;
    @BindView(R.id.stall_detail_state)
    StateLayout stateLayout;
   /* @BindView(R.id.cet_stall_detail_contact)
    TextView cetStallDetailContact;
    @BindView(R.id.cet_stall_detail_phone)
    TextView cetStallDetailPhone;*/
    @BindView(R.id.cet_stall_detail_description)
    EditText cetStallDetailDescription;
    private int stallId,stallTypeId;
    private ArrayList<ArrayList<StallTypeBean>> carType2 = new ArrayList<>();
    private ArrayList<StallTypeBean> carType1 = new ArrayList<>();
    private OptionsPickerView stallPicker,targetPicker;
    private TimePickerView buildTimePicker;
    private List<Object> photoList = new ArrayList<>();
    private String year = "";
    private int targetTag = 0;
    private String size,min_price,max_price = "";
    private List<FileBean> imgList = new ArrayList<>();
    private boolean isUpdate = false;
    private boolean isDetailQuest = true;
    @Override
    protected void init() {
        EventBus.getDefault().register(this);
        new CommonTitle.Builder(this).setTitle("车位详情").build().show();
        stallId = getIntent().getIntExtra("stall_id",0);
        getDetailInfo();
        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, @IdRes int checkedId) {
                if (checkedId == R.id.radio_have) {
                    tvStallDetailYear.setText("永久");
                    tvStallDetailYear.setEnabled(false);
                    year = "";
                } else {
                    tvStallDetailYear.setText(year);
                    tvStallDetailYear.setEnabled(true);
                }
            }
        });
        initPicker();
        avpStallDetailBanner.setOnPageItemClickListener(new AutoSlippingViewPager.OnPageItemClickListener() {
            @Override
            public void onItemClicked(int index) {
                startActivity(new Intent(StallDetailActivity.this,EditPhotoActivity.class)
                .putExtra("img_list", (Serializable) imgList)
                        .putExtra("stall_id",stallId));
            }
        });
        stateLayout.setOnRetryListener(new StateLayout.OnRetryListener() {
            @Override
            public void onRetry(int state) {
                getDetailInfo();
            }
        });
    }
    private void getDetailInfo () {
        isDetailQuest = true;
        HashMap<String,Object> map = HttpParamMap.getParamMap();
        map.put("id",stallId);
        mPresenter.getStallDetail(map);
    }
    @Override
    protected int getLayoutId() {
        return R.layout.activity_stall_detail;
    }

    @Override
    protected StallDetailPresenter createPresenter() {
        return new StallDetailPresenter();
    }

    @OnClick({R.id.iv_stall_detail_upload, R.id.tv_stall_detail_type, R.id.tv_stall_detail_area, R.id.tv_stall_detail_year, R.id.tv_stall_detail_build, R.id.tv_stall_detail_object, R.id.cet_stall_detail_min_price, R.id.cet_stall_detail_max_price, R.id.btn_stall_detail_sure})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_stall_detail_upload:
                ToastUtils.showShort("up;oad");
                break;
            case R.id.tv_stall_detail_type:
                if (carType1.size() > 0) {
                    stallPicker.show();
                } else {
                    getCarPlaceType();
                }
                break;
            case R.id.tv_stall_detail_area:
                ValueInputBoardDialog dialog3 = new ValueInputBoardDialog(this,size,ValueInputBoardDialog.UnitEnum.AREA);
                dialog3.setOnDialogResultListener(new ValueInputBoardDialog.OnDialogResultListener() {
                    @Override
                    public void onResult(String value, String unit) {
                        size = value;
                        tvStallDetailArea.setText(value + unit);
                    }
                });
                dialog3.show();
                break;
            case R.id.tv_stall_detail_year:
                ValueInputBoardDialog dialog = new ValueInputBoardDialog(this,year,ValueInputBoardDialog.UnitEnum.YEAR);
                dialog.setOnDialogResultListener(new ValueInputBoardDialog.OnDialogResultListener() {
                    @Override
                    public void onResult(String value, String unit) {
                        year = value;
                        tvStallDetailYear.setText(year + unit);
                    }
                });
                dialog.show();
                break;
            case R.id.tv_stall_detail_build:
                if (buildTimePicker != null) {
                    buildTimePicker.show();
                }
                break;
            case R.id.tv_stall_detail_object:
                if (targetPicker != null) {
                    targetPicker.show();
                }
                break;
            case R.id.cet_stall_detail_min_price:
                ValueInputBoardDialog dialog1 = new ValueInputBoardDialog(this,min_price,ValueInputBoardDialog.UnitEnum.SELL);
                dialog1.setOnDialogResultListener(new ValueInputBoardDialog.OnDialogResultListener() {
                    @Override
                    public void onResult(String value, String unit) {
                        min_price = value;
                        minPrice.setText(value + unit);
                    }
                });
                dialog1.show();
                break;
            case R.id.cet_stall_detail_max_price:
                ValueInputBoardDialog dialog2 = new ValueInputBoardDialog(this,max_price,ValueInputBoardDialog.UnitEnum.SELL);
                dialog2.setOnDialogResultListener(new ValueInputBoardDialog.OnDialogResultListener() {
                    @Override
                    public void onResult(String value, String unit) {
                        max_price = value;
                        maxPrice.setText(value + unit);
                    }
                });
                dialog2.show();
                break;
            case R.id.btn_stall_detail_sure:
                if (TextUtils.isEmpty(cetStallDetailTitle.getInputValue())) {
                   ToastUtils.showShort("标题不能为空");
                    return;
                }
                if (TextUtils.isEmpty(cetStallDetailNumber.getInputValue())) {
                    ToastUtils.showShort("车位编号不能为空");
                    return;
                }
                if (Double.parseDouble(min_price) > Double.parseDouble(max_price)) {
                    ToastUtils.showShort("最低价不能高于最高价");
                    return;
                }
                /**
                 * Id	int	是	车位id
                 Number	string	是	车位编号
                 FloorNum	string	是	楼层
                 SpaceType	int	是	车位类型
                 Size	int	是	面积
                 IsHaveSpace	int	是	是否有产权
                 DateLine	string	是	使用期限
                 SpaceBuildTime	string	是	建成时间
                 IsSaleToAll	int	是	销售对象
                 SpaceAdvan	string	是	区位优势
                 Price	int	是	价格
                 PriceMax	int	是	最高价格
                 Description	string	是	车位描述
                 */

                HashMap<String,Object> map = HttpParamMap.getParamMap();
                map.put("Id",stallId);
                map.put("Title",cetStallDetailTitle.getInputValue());
                map.put("Number",cetStallDetailNumber.getInputValue());
                map.put("FloorNum",cetStallDetailFloor.getInputValue());
                map.put("SpaceType",stallTypeId);
                map.put("Size",size);
                map.put("IsHaveSpace",radioGroup.getCheckedRadioButtonId()==R.id.radio_have?0:1);
                map.put("DateLine",year);
                map.put("SpaceBuildTime",tvStallDetailBuild.getText().toString());
                map.put("IsSaleToAll",targetTag);
                map.put("SpaceAdvan",cetStallDetailAdvantage.getInputValue());
                map.put("Price",min_price);
                map.put("PriceMax",max_price);
                map.put("Description",cetStallDetailDescription.getText().toString());
                mPresenter.saveStallDetail(map);
                break;
            default:
                break;
        }
    }

    private void getCarPlaceType() {
        mPresenter.getStallType(HttpParamMap.getParamMap());
    }

    private void initStallTypePicker() {
        stallPicker = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                String tx = carType1.get(options1).getName()+"-"+carType2.get(options1).get(option2).getName() ;
                tvStallDetailType.setText(tx);
                stallTypeId = carType2.get(options1).get(option2).getValue();
            }
        }).isDialog(false).build();
        stallPicker.setPicker(carType1,carType2);//添加数据
        stallPicker.show();
    }
    @Override
    public void onGetStallDetailSuccess(StallDetailBean data) {
        isDetailQuest = false;
        if (mIsLive && data != null) {
            stateLayout.showContent();
            photoList.clear();
            imgList.clear();
            for (int i = 0; i < data.getImgList().size(); i++) {
                photoList.add(data.getImgList().get(i).getPhotoUrl());
                imgList.add(new FileBean(data.getImgList().get(i).getId(),data.getImgList().get(i).getPhotoUrl()));
            }
            AutoSlipBanner.configBanner(avpStallDetailBanner,photoList);
            StallDetailBean.InfoBean infoBean = data.getInfo();
            cetStallDetailTitle.setText(infoBean.getTitle());
            cetStallDetailHouse.setText(infoBean.getName());
            cetStallDetailAddress.setText(infoBean.getAddress());
            cetStallDetailNumber.setText(infoBean.getNumber());
            cetStallDetailFloor.setText(infoBean.getFloorNum());
            tvStallDetailType.setText(infoBean.getSpaceTypeDesc());
            stallTypeId = infoBean.getSpaceType();
            tvStallDetailArea.setText(infoBean.getSize()+"㎡");
            size = infoBean.getSize()+"";
            minPrice.setText(infoBean.getPrice()+"元");
            min_price = infoBean.getPrice()+"";
            maxPrice.setText(infoBean.getPriceMax()+"元");
            max_price = infoBean.getPriceMax()+"";
            if (infoBean.getDateLine().endsWith("年")) {
                year = infoBean.getDateLine().substring(0,infoBean.getDateLine().toString().length()-1);
                tvStallDetailYear.setText(infoBean.getDateLine());
            } else {
                year = infoBean.getDateLine();
                tvStallDetailYear.setText(infoBean.getDateLine() + "年");
            }
            if (infoBean.getIsHaveSpace() == 0) {
                rbHave.setChecked(true);
                tvStallDetailYear.setText("永久");
                tvStallDetailYear.setEnabled(false);
            } else {
                rbNo.setChecked(true);
                tvStallDetailYear.setEnabled(true);
            }
            tvStallDetailBuild.setText(infoBean.getSpaceBuildTime());
            if (infoBean.getIsSaleToAll() == 0) {
                tvStallDetailObject.setText(DataServer.getSellObject().get(0));
                targetTag = 0;
            } else {
                tvStallDetailObject.setText(DataServer.getSellObject().get(1));
                targetTag = 1;
            }
            cetStallDetailAdvantage.setText(infoBean.getSpaceAdvan());
            cetStallDetailDescription.setText(infoBean.getDescription());

        }
    }

    @Override
    public void onGetStallTypeSuccess(List<StallTypeBean> data) {
        if (mIsLive && data != null) {
            for (int i = 0; i < data.size(); i++) {
                carType1.add(new StallTypeBean(data.get(i).getValue()
                        ,data.get(i).getName()));
                ArrayList<StallTypeBean> type1 = new ArrayList<>();
                for (int j = 0; j < data.get(i).getData().size(); j++) {
                    type1.add(new StallTypeBean
                            (data.get(i).getData().get(j).getValue(),data.get(i).getData().get(j).getName()));
                }
                carType2.add(type1);
            }
            initStallTypePicker();
        }
    }

    @Override
    public void onSaveStallDetailSuccess() {
        EventBus.getDefault().post(new AlterStallDetailEvent());
        finish();
    }

    /**
     * 初始化picker
     */
    private void initPicker() {
        targetPicker = new OptionsPickerView.Builder(this, new OptionsPickerView.OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int option2, int options3, View v) {
                //返回的分别是三个级别的选中位置
                tvStallDetailObject.setText(DataServer.getSellObject().get(options1));
                if (options1 == 0) {
                    targetTag = 0;
                } else {
                    targetTag = 1;
                }
            }
        }).isDialog(false).build();
        targetPicker.setPicker(DataServer.getSellObject());
        Calendar selectedDate = Calendar.getInstance();
        Calendar startDate = Calendar.getInstance();
        startDate.set(1920, 0, 1);
        Calendar endDate = Calendar.getInstance();
        endDate.set(2020, 0, 1);
        buildTimePicker = new TimePickerView.Builder(this, new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {//选中事件回调
                tvStallDetailBuild.setText(getTime(date));
            }
        })
                //年月日时分秒 的显示与否，不设置则默认全部显示
                .setType(new boolean[]{true, true, false, false, false, false})
                .setLabel("年", "月", "", "", "", "")
                .isCenterLabel(false)
                .setDividerColor(Color.DKGRAY)
                .setContentSize(21)
                .setDate(selectedDate)
                .setRangDate(startDate, endDate)
                .setDecorView(null)
                .build();
    }
    private String getTime(Date date) {//可根据需要自行截取数据显示
        SimpleDateFormat format = new SimpleDateFormat("yyyy年MM月");
        return format.format(date);
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEditPhotoFinishEvent(EditPhotoEvent event) {
        LogUtils.i("onEditPhotoFinishEvent", event.toString());
        List<FileBean> list = event.getList();
        if (list.size() > 0) {
            isUpdate = true;
            photoList.clear();
            imgList.clear();
            for (int i = 0; i < list.size(); i++) {
                if (list.get(i) != null && !TextUtils.isEmpty(list.get(i).getPath())) {
                    photoList.add(list.get(i).getPath());
                    imgList.add(new FileBean(list.get(i).getId(), list.get(i).getPath()));
                }
            }
            AutoSlipBanner.configBanner(avpStallDetailBanner, photoList);
        }
    }
    @Override
    protected void onDestroy() {
        if (avpStallDetailBanner != null) {
            avpStallDetailBanner.stopAutoSlipping();
        }
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void showError(int errorTag, String msg) {
        if (isDetailQuest) {
            if (errorTag == AppConstant.NET_ERROR_CODE) {
                stateLayout.showNetwork();
            } else {
                stateLayout.showError();
            }
        } else {
            super.showError(errorTag, msg);
        }

    }
}
